<template>
  <div class="dashboard-container">
    <el-row :gutter="20">
      <!-- 系统信息卡片 -->
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header">
            <span>系统信息</span>
            <el-button 
              style="float: right; padding: 3px 0" 
              type="text"
              @click="refreshSystemInfo">
              <i class="el-icon-refresh"></i> 刷新
            </el-button>
          </div>
          
          <el-row :gutter="20" v-if="systemInfo">
            <el-col :span="8">
              <div class="info-item">
                <span class="label">系统:</span>
                <span class="value">{{ systemInfo.os.distro }} {{ systemInfo.os.release }}</span>
              </div>
              <div class="info-item">
                <span class="label">内核:</span>
                <span class="value">{{ systemInfo.os.kernel }}</span>
              </div>
              <div class="info-item">
                <span class="label">架构:</span>
                <span class="value">{{ systemInfo.os.arch }}</span>
              </div>
            </el-col>
            
            <el-col :span="8">
              <div class="info-item">
                <span class="label">主机名:</span>
                <span class="value">{{ systemInfo.os.hostname }}</span>
              </div>
              <div class="info-item">
                <span class="label">CPU:</span>
                <span class="value">{{ systemInfo.cpu.model }}</span>
              </div>
              <div class="info-item">
                <span class="label">内存:</span>
                <span class="value">{{ systemInfo.memory.total }} GB</span>
              </div>
            </el-col>
            
            <el-col :span="8">
              <div class="info-item">
                <span class="label">运行时间:</span>
                <span class="value">{{ formatUptime(systemInfo.os.uptime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">进程:</span>
                <span class="value">{{ systemInfo.processes?.all || 0 }} (运行: {{ systemInfo.processes?.running || 0 }})</span>
              </div>
            </el-col>
          </el-row>
          
          <div v-else class="loading-container">
            <el-skeleton :rows="3" animated />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 资源使用率 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">CPU使用率</div>
          <div class="chart-container">
            <el-progress 
              type="dashboard" 
              :percentage="cpuUsage" 
              :color="getUsageColor(cpuUsage)">
              <div class="progress-text">{{ cpuUsage }}%</div>
            </el-progress>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">内存使用率</div>
          <div class="chart-container">
            <el-progress 
              type="dashboard" 
              :percentage="memoryUsage" 
              :color="getUsageColor(memoryUsage)">
              <div class="progress-text">{{ memoryUsage }}%</div>
            </el-progress>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card shadow="hover">
          <div slot="header">磁盘使用率</div>
          <div class="chart-container">
            <el-progress 
              type="dashboard" 
              :percentage="diskUsage" 
              :color="getUsageColor(diskUsage)">
              <div class="progress-text">{{ diskUsage }}%</div>
            </el-progress>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 服务状态 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header">服务状态</div>
          <el-table :data="serviceData" v-loading="loading">
            <el-table-column prop="name" label="服务名称"></el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-tag :type="scope.row.running ? 'success' : 'danger'">
                  {{ scope.row.running ? '运行中' : '已停止' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="port" label="端口"></el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button 
                  size="mini" 
                  type="primary" 
                  @click="handleServiceAction(scope.row, 'start')"
                  :disabled="scope.row.running">
                  启动
                </el-button>
                <el-button 
                  size="mini" 
                  type="danger" 
                  @click="handleServiceAction(scope.row, 'stop')"
                  :disabled="!scope.row.running">
                  停止
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { mockSystemInfo, mockServices } from '@/utils/mock'

export default {
  name: 'DashboardPage',
  data() {
    return {
      loading: true,
      serviceData: [],
      useMockData: true // 在后端API准备好前使用模拟数据
    }
  },
  computed: {
    ...mapGetters([
      'isAdmin'
    ]),
    systemInfo() {
      // 优先使用Vuex中的数据，如果没有则使用模拟数据
      return this.$store.state.systemInfo || (this.useMockData ? mockSystemInfo : null)
    },
    cpuUsage() {
      return this.systemInfo ? parseFloat(this.systemInfo.cpu.load) : 0
    },
    memoryUsage() {
      return this.systemInfo ? parseFloat(this.systemInfo.memory.usedPercent) : 0
    },
    diskUsage() {
      if (!this.systemInfo || !this.systemInfo.disk.length) return 0
      // 取主分区的使用率
      const rootDisk = this.systemInfo.disk.find(disk => disk.mount === '/')
      return rootDisk ? parseFloat(rootDisk.usedPercent) : 0
    }
  },
  created() {
    this.getServiceStatus()
    this.refreshSystemInfo()
  },
  methods: {
    // 获取服务状态
    getServiceStatus() {
      this.loading = true
      
      if (this.useMockData) {
        // 使用模拟数据
        const services = mockServices
        const serviceList = []
        
        // 转换服务数据为表格数据
        for (const [name, status] of Object.entries(services)) {
          const serviceInfo = {
            name: this.getServiceDisplayName(name),
            id: name,
            running: status === 'active',
            port: this.getServicePort(name)
          }
          serviceList.push(serviceInfo)
        }
        
        this.serviceData = serviceList
        this.loading = false
      } else {
        // 使用实际API
        this.$http.get('/system/services')
          .then(res => {
            const services = res.data
            const serviceList = []
            
            // 转换服务数据为表格数据
            for (const [name, status] of Object.entries(services)) {
              const serviceInfo = {
                name: this.getServiceDisplayName(name),
                id: name,
                running: status === 'active',
                port: this.getServicePort(name)
              }
              serviceList.push(serviceInfo)
            }
            
            this.serviceData = serviceList
            this.loading = false
          })
          .catch(() => {
            this.loading = false
            // 如果API调用失败，切换到模拟数据
            this.useMockData = true
            this.getServiceStatus()
          })
      }
    },
    
    // 刷新系统信息
    refreshSystemInfo() {
      if (this.useMockData) {
        // 使用模拟数据
        this.$store.commit('SET_SYSTEM_INFO', mockSystemInfo)
      } else {
        // 使用实际API
        this.$store.dispatch('getSystemInfo').catch(() => {
          // 如果API调用失败，切换到模拟数据
          this.useMockData = true
          this.$store.commit('SET_SYSTEM_INFO', mockSystemInfo)
        })
      }
    },
    
    // 格式化运行时间
    formatUptime(seconds) {
      const days = Math.floor(seconds / 86400)
      const hours = Math.floor((seconds % 86400) / 3600)
      const minutes = Math.floor((seconds % 3600) / 60)
      
      if (days > 0) {
        return `${days}天 ${hours}小时 ${minutes}分钟`
      } else if (hours > 0) {
        return `${hours}小时 ${minutes}分钟`
      } else {
        return `${minutes}分钟`
      }
    },
    
    // 获取使用率颜色
    getUsageColor(percentage) {
      if (percentage < 60) {
        return '#67C23A'
      } else if (percentage < 80) {
        return '#E6A23C'
      } else {
        return '#F56C6C'
      }
    },
    
    // 服务操作
    handleServiceAction(service, action) {
      if (!this.isAdmin) {
        this.$message.warning('需要管理员权限进行此操作')
        return
      }
      
      this.$confirm(`确定要${action === 'start' ? '启动' : '停止'}服务 ${service.name} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        
        if (this.useMockData) {
          // 模拟操作成功
          this.$message.success(`${action === 'start' ? '启动' : '停止'}服务成功`)
          // 更新模拟服务状态
          mockServices[service.id] = action === 'start' ? 'active' : 'inactive'
          // 刷新服务状态
          this.getServiceStatus()
        } else {
          // 使用实际API
          this.$http.post('/system/services/action', {
            service: service.id,
            action
          }).then(() => {
            this.$message.success(`${action === 'start' ? '启动' : '停止'}服务成功`)
            // 刷新服务状态
            this.getServiceStatus()
          }).catch(error => {
            this.$message.error(error.response?.data?.error || '操作失败')
            this.loading = false
          })
        }
      }).catch(() => {})
    },
    
    // 获取服务显示名称
    getServiceDisplayName(service) {
      const names = {
        nginx: 'Nginx服务器',
        mysql: 'MySQL数据库',
        mongodb: 'MongoDB数据库',
        redis: 'Redis缓存',
        docker: 'Docker容器',
        ssh: 'SSH服务'
      }
      
      return names[service] || service
    },
    
    // 获取服务端口
    getServicePort(service) {
      const ports = {
        nginx: 80,
        mysql: 3306,
        mongodb: 27017,
        redis: 6379,
        docker: '-',
        ssh: 22
      }
      
      return ports[service] || '-'
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  padding: 0;
}

.info-item {
  margin-bottom: 10px;
  display: flex;
}

.label {
  font-weight: bold;
  width: 80px;
}

.value {
  flex: 1;
}

.chart-container {
  height: 180px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.progress-text {
  font-size: 16px;
  font-weight: bold;
}

.loading-container {
  padding: 20px 0;
}
</style> 